package com.zhj.bz.datastructure.stack;

import java.util.Scanner;

/**
 * @author zhj
 */
public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);

        while (loop) {
            System.out.println("show:展示栈");
            System.out.println("exit:退出");
            System.out.println("push:入栈");
            System.out.println("pop:出栈");
            System.out.println("请输入你的选择");
            key = scanner.next();
            switch (key) {
                case "show":
                    arrayStack.show();
                    break;
                case "exit":
                    System.out.println("程序结束");
                    loop = false;
                    break;
                case "push":
                    System.out.println("请输入一个数字：");
                    int num = scanner.nextInt();
                    arrayStack.push(num);
                    break;
                case "pop":
                    try {
                        System.out.println("出栈的数据是" + arrayStack.pop());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    System.out.println("输入非法指令");
                    break;
            }
        }
    }
}

class ArrayStack {
    // 最大长度
    private int maxSize;
    // 数组模拟栈
    private int[] stack;
    // 栈顶指针，初始化为-1
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    // 栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 栈空
    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int n) {
        if (isFull()) {
            System.out.println("栈满不能插入");
            return;
        }
        top++;
        stack[top] = n;
    }

    // 出栈
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈是空的");
        }
        top--;
        return stack[top+1];
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("栈是空的");
        }
        for (int i = top; i >= 0; i--) {
            System.out.print(stack[i] + "\t");
        }
        System.out.println();
    }
}
